package com.cpos.base.handler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

/*
*  @创建人 Cpos_wl
*  @创建时间 2020/5/27
   @描述   项目全局拦截器
*/


//@Configuration
public class CposHandlerInterceptor implements WebMvcConfigurer {

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return  new SecurityInterceptor();
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{
            HttpSession session = request.getSession();
            //判断是否已有该用户登录的session
            if(session.getAttribute("username") !=null){
                return  true;
            }else {
                System.out.println("没有session");
                response.sendRedirect(request.getContextPath()+"/view/login.html");
                return true;
            }
        }
    }

    @Override
    public  void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //拦截配置
        addInterceptor.addPathPatterns("/**");
        //排除配置
        addInterceptor.excludePathPatterns("/bkge/**","/view/css/**","/view/images/**","/view/js/**","/view/login.html");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //设置允许跨域的路径
                .allowedOrigins("*") //设置允许跨域请求用的域名
                .allowCredentials(true) //是否设置证书 不再默认开启
                .allowedMethods("GET","POST","PUT","DELETE")//设置允许的方法
                .maxAge(3600); //设置跨域允许时间


    }
}
